

local modid = 'webber_the_trainer' -- 唯一识别id
local container_prefabid = 'webbert_seedbox'
-------------------------------------------------
--------------生成种子匣需要的信息表---------------
-------------------------------------------------
if TUNING.MOD_WEBBER_THE_TRAINER.map_seeds == nil then
    ---真空种子匣UI用到的信息表
    ---@type table<string,{name_seed:string,name_plant:string|nil,xml:string,tex:string}>
    TUNING.MOD_WEBBER_THE_TRAINER.map_seeds = {}
end
---(其他种子, 对应作物)
local irregular_seeds = {
    pinecone = "evergreen",
    acorn = "deciduoustree",
    marblebean = "marbletree",
    palmcone_seed = "palmconetree",
    twiggy_nut = "twiggytree",
    ancienttree_seed = nil,
}
for k, v in pairs(irregular_seeds) do
    TUNING.MOD_WEBBER_THE_TRAINER.map_seeds[k] = {
        name_seed = STRINGS.NAMES[string.upper(k)],
        name_plant = v and STRINGS.NAMES[string.upper(v)] or '',
        tex = k..".tex",
        xml = GetInventoryItemAtlas(k..".tex") or '',
    }
end
---种子ui默认排序. 当该表中的种子找不到时, 会尝试生成对应的信息(如果找不到xml,则不会添加进种子表中), 因此其他mod只需要延迟一帧将种子添加到该表即可.
---<br>可以不用管唯一性, 重复的会跳过
TUNING.MOD_WEBBER_THE_TRAINER.seed_ui_order = {
    'seeds',
    'tomato_seeds',
    'potato_seeds',
    'garlic_seeds',
    'pepper_seeds',
    'dragonfruit_seeds',
    'asparagus_seeds',
    'pumpkin_seeds',
    'corn_seeds',
    'onion_seeds',
    'pomegranate_seeds',
    'eggplant_seeds',
    'watermelon_seeds',
    'durian_seeds',
    'carrot_seeds',
    'pinecone',
    'acorn',
    'marblebean',
    'palmcone_seed',
    'twiggy_nut',
    'ancienttree_seed',
    -- 能力勋章
    'mandrake_seeds',
    'medal_weed_seeds',
    'immortal_fruit_seed',
    'medal_gift_fruit_seed',
    -- 棱镜
    'pineananas_seeds',
}
-- 官方种子
AddSimPostInit(function ()
    if TheWorld then
        -- 延迟1秒
        TheWorld:DoTaskInTime(1,function ()
            local farm_plant_defs = require('prefabs/farm_plant_defs').PLANT_DEFS
            for k,v in pairs(farm_plant_defs) do
                local seed_prefabid = k..'_seeds'
                local plant_prefabid = 'farm_plant_'..k
                if GLOBAL.Prefabs[seed_prefabid] and GLOBAL.Prefabs[plant_prefabid] then
                    TUNING.MOD_WEBBER_THE_TRAINER.map_seeds[seed_prefabid] = {
                        name_seed = STRINGS.NAMES[string.upper(seed_prefabid)],
                        name_plant = STRINGS.NAMES[string.upper(k)],
                        tex = seed_prefabid..".tex",
                        xml = GetInventoryItemAtlas(seed_prefabid..".tex") or '',
                    }
                end
            end

            -- 检查排序表, 如果没有, 则添加到种子表种
            for _,v in ipairs(TUNING.MOD_WEBBER_THE_TRAINER.seed_ui_order) do
                if TUNING.MOD_WEBBER_THE_TRAINER.map_seeds[v] == nil then
                    local tex = v .. '.tex'
                    local xml = GetInventoryItemAtlas(tex,true) or nil
                    if xml then -- 如果找到了xml才添加
                        TUNING.MOD_WEBBER_THE_TRAINER.map_seeds[v] = {
                            name_seed = STRINGS.NAMES[string.upper(v)],
                            name_plant = '',
                            tex = tex,
                            xml = xml,
                        }
                    end
                end
            end
        end)
    end
end)
-------------------------------------------------
-- local Image = require "widgets/image"
-- local ImageButton = require "widgets/imagebutton"
-- local Text = require "widgets/text"
-- local UIAnim = require "widgets/uianim"
-- local TextEdit = require "widgets/textedit"
local TEMPLATES = require "widgets/redux/templates"
---@type widget_scrollablelist
local ScrollableList = require "widgets/scrollablelist"
local webbert_seedbox_seed = require('core_webber_the_trainer/widgets/webbert_seedbox_seed')

local function checkTarContainer(m,id)
    return m.container and m.container.prefab == id and m.container or nil
end

---@class widget_containerwidget_webbert_seedbox : widget_containerwidget
-- -@field check_map_webbert_seedbox_scrolllist_item table<string,integer> # scrolllist 第一个参数 只能传数组 , 所以单独弄个字典来判断某个项目是否存在
---@field webbert_seedbox_scrolllist_item widget_webbert_seedbox_seed[] # scrolllist 第一个参数
---@field webbert_seedbox_scrolllist widget_scrollablelist 
---@field webbert_seedbox_scrolllist_item_map table<string,widget_webbert_seedbox_seed> # 换了个更保险的字典,直接引用的scrolllist的item

AddClassPostConstruct('widgets/containerwidget',
---comment
---@param self widget_containerwidget_webbert_seedbox
---@param ... unknown
function (self, ...)

    ---@class ent_webbert_seedbox : ent
    ---@field _invimg_no integer|nil # 容器UI格子背景图切换序号
    ---@field webbert_seedbox_isopen boolean|nil # 容器是否打开
    ---@field webbert_seedbox_containerwidget widget_containerwidget_webbert_seedbox # refer

    local old_Open = self.Open
    function self:Open(container, doer, ...)
        if old_Open ~= nil then
            old_Open(self, container, doer, ...)
        end
        ---@type ent_webbert_seedbox|nil
        local box = checkTarContainer(self,container_prefabid)
        if box and box.replica.webbert_seedbox then
            self.inv[1].bgimage:SetScale(2,2,1)
            self:StartUpdating()
            -- self.bganim:SetScale(1.7,1.85,1)
            self.bganim:SetScale(2.7,2.5,1)
            -- 操作种子匣时 禁止玩家控制
            self:SetOnGainFocus(function()
                if ThePlayer then
                    -- ThePlayer.components.playercontroller:Enable(false)
                    if ThePlayer.components.playercontroller then
                        ThePlayer.components.playercontroller.classified.iscontrollerenabled:set_local(false)
                    end
                end
            end)
            self:SetOnLoseFocus(function ()
                if ThePlayer then
                    -- ThePlayer.components.playercontroller:Enable(true)
                    if ThePlayer.components.playercontroller then
                        ThePlayer.components.playercontroller.classified.iscontrollerenabled:set_local(true)
                    end
                end
            end)

            -- self.check_map_webbert_seedbox_scrolllist_item = nil
            -- self.check_map_webbert_seedbox_scrolllist_item = {}
            for k,_ in pairs(self.webbert_seedbox_scrolllist_item or {}) do
                if self.webbert_seedbox_scrolllist_item[k] then
                    self.webbert_seedbox_scrolllist_item[k]:Kill()
                    self.webbert_seedbox_scrolllist_item[k] = nil
                end
            end
            self.webbert_seedbox_scrolllist_item = nil
            self.webbert_seedbox_scrolllist_item = {}

            self.webbert_seedbox_scrolllist_item_map = nil
            self.webbert_seedbox_scrolllist_item_map = {}

            local map_nutrients = TUNING.MOD_WEBBER_THE_TRAINER.map_nutrients
            local order = TUNING.MOD_WEBBER_THE_TRAINER.seed_ui_order
            local count = 0
            for i,v in ipairs(order) do
                local map_seeds = TUNING.MOD_WEBBER_THE_TRAINER.map_seeds
                -- 只有该种子存在 并且 没有添加过 , 才允许添加
                -- if map_seeds[v] and not self.check_map_webbert_seedbox_scrolllist_item[v] then
                if map_seeds[v] and not self.webbert_seedbox_scrolllist_item_map[v] then
                    local member = webbert_seedbox_seed(map_seeds[v].name_seed,map_seeds[v].name_plant,map_seeds[v].xml,map_seeds[v].tex,box,v)
                    local num = box.replica.webbert_seedbox.map[v] or 0
                    member:SetSeedsNum(num)
                    -- 设置肥料
                    if map_nutrients and map_nutrients[v] and map_nutrients[v].nutrient and map_nutrients[v].nutrient[1] then
                        member:SetNutrients(map_nutrients[v].nutrient[1],map_nutrients[v].nutrient[2],map_nutrients[v].nutrient[3])
                    end
                    member:SetScale(1.2,1.2)
                    count = count + 1
                    -- self.check_map_webbert_seedbox_scrolllist_item[v] = count
                    table.insert(self.webbert_seedbox_scrolllist_item,member)
                    self.webbert_seedbox_scrolllist_item_map[v] = member
                end
            end
            -- local count = 0
            -- for k,v in pairs(TUNING.MOD_WEBBER_THE_TRAINER.map_seeds or {}) do
            --     local member = webbert_seedbox_seed(v.name_seed,v.name_plant,v.xml,v.tex)
            --     local num = box.replica.webbert_seedbox.map[k] or 0
            --     member:SetSeedsNum(num)
            --     count = count + 1
            --     self.check_map_webbert_seedbox_scrolllist_item[k] = count
            --     table.insert(self.webbert_seedbox_scrolllist_item,member)
            -- end
            if self.webbert_seedbox_scrolllist then
                self.webbert_seedbox_scrolllist:Kill()
                self.webbert_seedbox_scrolllist = nil
            end
            self.webbert_seedbox_scrolllist = self:AddChild(ScrollableList( self.webbert_seedbox_scrolllist_item, 600, 480, 65, 10, nil, nil, 30, nil, nil, nil, nil, nil, 'GOLD'))
            self.webbert_seedbox_scrolllist:SetPosition(-5,-70)

            -- 挂一下
            box.webbert_seedbox_containerwidget = self

            box.webbert_seedbox_isopen = true

            -- 重新进入加载范围时,请求同步一次数据
            if not box.replica.webbert_seedbox.loaded then
                box.replica.webbert_seedbox.loaded = true
                SendModRPCToServer(GetModRPC(modid,modid..'webbert_seedbox_forcesync'),box)
            end

        end
    end

    local old_Close = self.Close
    function self:Close(...)
        if old_Close then
            old_Close(self,...)
        end
        ---@type ent_webbert_seedbox|nil
        local box = checkTarContainer(self,container_prefabid)
        if box then
            self:StopUpdating()
            box.webbert_seedbox_isopen = false
        end
    end

    local old_OnUpdate = self.OnUpdate
    function self:OnUpdate(dt)
        if TheNet:IsServerPaused() then return end
        if old_OnUpdate ~= nil then
            old_OnUpdate(self, dt)
        end
        ---@type ent_webbert_seedbox|nil
        local box = checkTarContainer(self,container_prefabid)
        if box then
            box._invimg_no = (box._invimg_no or 1) % 96 + 1
            self.inv[1].bgimage:SetTexture('images/frames/merged_img_1750061493.xml', box._invimg_no..'.tex')
        end
    end
end)

AddModRPCHandler(modid,modid..'webbert_seedbox_btn',
---comment
---@param player ent
---@param box ent_webbert_seedbox
---@param seed_prefab PrefabID
function (player,box,seed_prefab)
    if player and player.components.inventory and box and box.components.webbert_seedbox then
        local map = box.components.webbert_seedbox.map
        local cur_num = map[seed_prefab] or 0
        if cur_num > 0 then
            local seeds = box.components.webbert_seedbox:FetchSeeds(seed_prefab)
            if seeds then
                local activeitem = player.components.inventory:GetActiveItem()
                local pt = player:GetPosition()
                if activeitem and activeitem:IsValid() then
                    player.components.inventory:GiveItem(seeds,nil,pt)
                else
                    player.components.inventory:GiveActiveItem(seeds)
                end
            end
        end
    end
end)

AddModRPCHandler(modid,modid..'webbert_seedbox_btn_drop',
---comment
---@param player ent
---@param box ent_webbert_seedbox
---@param seed_prefab PrefabID
function (player,box,seed_prefab)
    if player and player.components.inventory and box and box.components.webbert_seedbox then
        local map = box.components.webbert_seedbox.map
        local cur_num = map[seed_prefab] or 0
        if cur_num > 0 then
            local seeds = box.components.webbert_seedbox:FetchSeeds(seed_prefab)
            if seeds then
                local pt = player:GetPosition()
                seeds.Transform:SetPosition(pt:Get())
            end
        end
    end
end)

AddModRPCHandler(modid,modid..'webbert_seedbox_forcesync',
---comment
---@param player ent
---@param box ent_webbert_seedbox
function (player,box)
    if player and player.components.inventory and box and box.components.webbert_seedbox then
        box.components.webbert_seedbox:ForceSync()
    end
end)
